package com.label.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.label.common.CommonResult;
import com.label.config.TokenUtil;
import com.label.entity.Log;
import com.label.entity.User;
import com.label.service.LogService;
import com.label.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Jianhua
 * @since 2022-03-27
 */
@Api
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    LogService logService;
@Autowired
    UserService userService;
@RequestMapping("/list")
    CommonResult list(ModelMap modelMap, Page page, @ModelAttribute("user")User user){
    page =userService.pageList(page,user);
    modelMap.addAttribute("page",page);
    return CommonResult.success(page);
}
    @CrossOrigin(origins = "http://localhost:8001")
    @RequestMapping(value = "/login")
    @ApiOperation("登录验证接口")
    CommonResult login1(HttpSession session, String username, String password){
    User user=new User(username,password);
        System.out.println(userService.select(username));
    if (!userService.select(username)){
       return CommonResult.loginfailed();
    }
    if (userService.login(user)){
        session.setAttribute("username",username);
        session.setMaxInactiveInterval(0);
        System.out.println(session.getAttribute("username"));
        String token =TokenUtil.sign(user);
        if (token!=null){
            //        日志记录
            Log log=new Log();
            log.setUsername((String) session.getAttribute("username"));
            log.setOperationType("系统登录");
            log.setOperationtime(LocalDateTime.now());
            logService.logsave(log);
            return CommonResult.token(token);
        }
    }
    return CommonResult.notoken("null");
}

@RequestMapping("/save")
    CommonResult save(User user){
    return CommonResult.success(userService.saveOrUpdate(user));
}
//id查询
@RequestMapping("/getByid")
    CommonResult getByid(Integer id){
    return CommonResult.success(userService.getById(id));
}
//逻辑删除
@RequestMapping("/del")
    CommonResult del(Integer id){
    User user=userService.getById(id);
   // user.setUserState("o");
    return CommonResult.success(userService.updateById(user));
}
//批量删除
@RequestMapping("/delByIds")
    CommonResult delByIds(Integer[] id){
    return CommonResult.success(userService.removeByIds(Arrays.asList(id)));
}
}
